package com.grm.security.login;

import com.alibaba.fastjson.JSON;
import com.grm.common.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录失败处理程序
 *
 * @author gaorimao
 * @date 2022-02-04
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        Result result = Result.failed(500,exception.getMessage());
        String jsonResult = JSON.toJSONString(result);
        PrintWriter out = response.getWriter();
        out.write(jsonResult);
        out.flush();
        out.close();
    }
}
